package com.vip.common.util;

import java.util.concurrent.CountDownLatch;

/**
 * 闭锁机制
 *
 * @author wgb
 * @date 2020/6/15 15:39
 */
public class LatchUtils {
    /**
     * 一次性启动全部任务
     *
     * @param row 并发数量
     * @param task  要执行的任务
     * @throws InterruptedException
     */
    public static void startTaskAllInOnce(int row, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(row);
        for (int i = 0; i < row; i++) {
            Thread t = new Thread(() -> {
                try {
                    // 使线程在此等待，当开始门打开时，一起涌入门中
                    startGate.await();
                    try {
                        task.run();
                    } finally {
                        // 将结束门减1，减到0时，就可以开启结束门了
                        endGate.countDown();
                    }
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            });
            t.start();
        }
        // 因开启门只需一个开关，所以立马就开启开始门
        startGate.countDown();
        // 等等结束门开启
        endGate.await();
    }
}